package thread.threaddemo;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: wenjingyuan
 * @Date: 2022/11/19/20:56
 * @Description:
 */
public class ThreadLock2 {
    private  static int number=0;
    //定义一个内部类
    static class Counter{
        private static Lock lock=new ReentrantLock();
        private static int MAX_Counter=100000;

        public  static void incr(){
            for (int i = 0; i < MAX_Counter; i++) {
                lock.lock();
                try{
                    number++;
                }finally {
                    lock.unlock();
                }

            }
        }
        public  static void decr(){
            for (int i = 0; i < MAX_Counter; i++) {
                lock.lock();
                try{
                    number--;
                }finally {
                    lock.unlock();
                }
            }

        }
    }
    public static void main(String[] args) throws InterruptedException {

        Thread t1=new Thread(()->{
            Counter.incr();
        });
        t1.start();
        Thread t2=new Thread(()->{
            Counter.decr();
        });
        t2.start();

        t1.join();
        t2.join();

        System.out.println("最终的结果"+ number);
    }
}
